package com.cuit.zuke.data.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuit.zuke.data.listener.DictListener;
import com.cuit.zuke.data.mapper.DictMapper;
import com.cuit.zuke.data.model.entity.Dict;
import com.cuit.zuke.data.model.vo.DictEeVo;
import com.cuit.zuke.data.service.DictService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * 查询子节点
     * @param id
     * @return 子节点
     */
    @Override
    @Cacheable(value = "dict")  //返回的集合会放到缓存中
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        for (Dict dict : dicts) {
            boolean t = this.hasChild(dict.getId());
            dict.setHasChildren(t);
        }
        return dicts;
    }

    /**
     * 导出数据字典
     * @param response
     * @return void
     */
    @Override
    @CacheEvict(value = "dict", allEntries = true)   //清空dict规则下的缓存内容
    public void exportDictData(HttpServletResponse response) {
        // 设置以下载方式打开
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String filename = "dict";
        response.setHeader("Content-disposition", "attachment;filename=" + filename + ".xlsx");

        // 查询数据库
        List<Dict> dictList = baseMapper.selectList(null);

        // dict -> dictVO
        List<DictEeVo> dictEeVoList = new ArrayList<>(dictList.size());
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            // spring自带工具类，将dict中内容copy到dictEeVo
            BeanUtils.copyProperties(dict, dictEeVo);
            dictEeVoList.add(dictEeVo);
        }

        // 写excel
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("dice").doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入excel到数据库
     * @param file excel表文件
     * @return void
     */
    @Override
    public void importDictFile(MultipartFile file) {
        try {
            // 因为dictMapper继承了baseMapper，所以这里可以传入baseMapper
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据dictCode和value查询dictName
     * @param dictCode dictCode
     * @param value value
     * @return dictName
     */
    @Override
    public String getDictName(String dictCode, String value) {
        // 如果dictCode为空，根据value查询
        if (StringUtils.isEmpty(dictCode)) {
            // 根据value查询
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(queryWrapper);
            return dict.getName();
        } else {
            // 根据dictCode查询dict对象，得到dict的id值
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dict_code", dictCode);
            Dict dict = baseMapper.selectOne(queryWrapper);
            Long parentId = dict.getId();

            // 根据parentId和value联合查询s
            QueryWrapper<Dict> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("parent_id", parentId);
            queryWrapper1.eq("value", value);
            Dict resultDict = baseMapper.selectOne(queryWrapper1);
            return resultDict.getName();
        }

    }


    /**
     * 根据dictCode获取下级节点
     * @param dictCode
     * @return 下级节点
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper1);
        Long id = dict.getId();

        List<Dict> dictList = this.findChildData(id);

        return dictList;
    }

    /**
     * 判断id下是否有子节点
     * @param id id
     * @return 1 or 0
     */
    private boolean hasChild(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }

    /**
     * 根据id获得name
     */
    public String getNameById(Long id){
        Dict dict = baseMapper.selectById(id);
        return dict.getName();
    }
}
